const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 初始化数据库
const db = new sqlite3.Database('news.db');

// 创建表
db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS posts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        author TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);

    db.run(`CREATE TABLE IF NOT EXISTS comments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        post_id INTEGER NOT NULL,
        content TEXT NOT NULL,
        author TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE
    )`);
});

// API路由

// 获取所有文章
app.get('/api/posts', (req, res) => {
    db.all(`SELECT * FROM posts ORDER BY created_at DESC`, (err, rows) => {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        res.json(rows);
    });
});

// 获取单篇文章及其评论
app.get('/api/posts/:id', (req, res) => {
    const postId = req.params.id;
    
    db.get(`SELECT * FROM posts WHERE id = ?`, [postId], (err, post) => {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        if (!post) {
            res.status(404).json({ error: '文章未找到' });
            return;
        }
        
        db.all(`SELECT * FROM comments WHERE post_id = ? ORDER BY created_at ASC`, [postId], (err, comments) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({ ...post, comments });
        });
    });
});

// 创建新文章
app.post('/api/posts', (req, res) => {
    const { title, content, author } = req.body;
    
    if (!title || !content || !author) {
        res.status(400).json({ error: '标题、内容和作者都是必填项' });
        return;
    }
    
    db.run(`INSERT INTO posts (title, content, author) VALUES (?, ?, ?)`, 
        [title, content, author], function(err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        
        db.get(`SELECT * FROM posts WHERE id = ?`, [this.lastID], (err, post) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json(post);
        });
    });
});

// 添加评论
app.post('/api/posts/:id/comments', (req, res) => {
    const postId = req.params.id;
    const { content, author } = req.body;
    
    if (!content || !author) {
        res.status(400).json({ error: '内容和作者都是必填项' });
        return;
    }
    
    db.run(`INSERT INTO comments (post_id, content, author) VALUES (?, ?, ?)`,
        [postId, content, author], function(err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        
        db.get(`SELECT * FROM comments WHERE id = ?`, [this.lastID], (err, comment) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json(comment);
        });
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 优雅关闭
process.on('SIGINT', () => {
    db.close((err) => {
        if (err) {
            console.error(err.message);
        }
        console.log('数据库连接已关闭');
        process.exit(0);
    });
});
